<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
        <p>{{ isLogin ? '欢迎回来，请登录您的账户' : '创建新账户' }}</p>
      </div>

      <!-- 切换按钮 -->
      <div class="mode-switch">
        <div class="switch-slider" :class="{ 'slide-right': !isLogin }"></div>
        <button 
          :class="['switch-btn', { active: isLogin }]" 
          @click="switchMode(true)"
        >
          登录
        </button>
        <button 
          :class="['switch-btn', { active: !isLogin }]" 
          @click="switchMode(false)"
        >
          注册
        </button>
      </div>

      <!-- 登录表单 -->
      <form v-if="isLogin" @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <input 
            v-model="loginForm.username" 
            type="text" 
            placeholder="用户名" 
            required
            :disabled="loading"
          />
        </div>
        <div class="form-group">
          <input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="密码" 
            required
            :disabled="loading"
          />
        </div>
        <button type="submit" class="submit-btn" :disabled="loading">
          <span v-if="loading">登录中...</span>
          <span v-else>登录</span>
        </button>
      </form>

      <!-- 注册表单 -->
      <form v-else @submit.prevent="handleRegister" class="login-form">
        <div class="form-group">
          <input 
            v-model="registerForm.username" 
            type="text" 
            placeholder="用户名" 
            required
            minlength="3"
            maxlength="20"
            :disabled="registerLoading"
          />
        </div>
        <div class="form-group">
          <input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="密码" 
            required
            minlength="6"
            :disabled="registerLoading"
          />
        </div>
        <div class="form-group">
          <input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="确认密码" 
            required
            :disabled="registerLoading"
          />
        </div>
        <button type="submit" class="submit-btn" :disabled="registerLoading">
          <span v-if="registerLoading">注册中...</span>
          <span v-else>注册</span>
        </button>
      </form>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { login, register } from '../api/auth'

const router = useRouter()
const isLogin = ref(true)
const loading = ref(false)
const registerLoading = ref(false)
const errorMessage = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

// 切换登录/注册模式
function switchMode(mode) {
  if (isLogin.value === mode) return;
  isLogin.value = mode;
  errorMessage.value = '';
  if (mode) {
    // 切换到登录模式时，只清空密码
    loginForm.password = '';
  } else {
    // 切换到注册模式时，清空注册表单
    Object.assign(registerForm, { username: '', password: '', confirmPassword: '' });
  }
}

// 处理登录
async function handleLogin() {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await login({
      username: loginForm.username,
      password: loginForm.password
    });
    if (response && response.Code === 200) {
      const user = response.Data || {};
      localStorage.setItem('token', user.token || '');
      localStorage.setItem('isLogin', 'true');
      localStorage.setItem('username', user.username || loginForm.username);
      localStorage.setItem('userId', user.userId || '');
      localStorage.setItem('justLoggedIn', 'true');
      router.replace('/dashboard');
    } else {
      errorMessage.value = response?.Message || String(response?.Code) || '登录失败';
      // 登录失败时只清空密码，保留用户名
      loginForm.password = '';
    }
  } catch (error) {
    console.error('❌ [Login] Error:', error);
    if (error.response && error.response.data && error.response.data.Message) {
      errorMessage.value = error.response.data.Message;
    } else if (error.response && error.response.data && error.response.data.Code) {
      errorMessage.value = String(error.response.data.Code);
    } else {
      errorMessage.value = error.message || '登录失败';
    }
    // 登录失败时只清空密码，保留用户名
    loginForm.password = '';
  } finally {
    loading.value = false;
  }
}

// 处理注册
async function handleRegister() {
  registerLoading.value = true
  errorMessage.value = ''
  if (registerForm.password !== registerForm.confirmPassword) {
    errorMessage.value = '两次输入的密码不一致'
    registerLoading.value = false
    return
  }
  try {
    const response = await register({
      username: registerForm.username,
      password: registerForm.password
    })
    console.log('🔍 [Register] Response:', response)
    if (response && response.Code === 200) {
      showMessage('注册成功！请登录您的账户', 'success')
      isLogin.value = true
      Object.assign(loginForm, { username: registerForm.username, password: '' })
    } else {
      errorMessage.value = response?.Message || String(response?.Code) || '注册失败'
    }
  } catch (error) {
    console.error('❌ [Register] Error:', error)
    if (error.response && error.response.data && error.response.data.Message) {
      errorMessage.value = error.response.data.Message
    } else if (error.response && error.response.data && error.response.data.Code) {
      errorMessage.value = String(error.response.data.Code)
    } else {
      errorMessage.value = error.message || '注册失败'
    }
  } finally {
    registerLoading.value = false
  }
}

// 显示消息提示
function showMessage(message, type = 'info') {
  const messageEl = document.createElement('div')
  messageEl.className = `message ${type}`
  messageEl.textContent = message
  messageEl.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 16px 24px;
    border-radius: 8px;
    color: white;
    font-size: 14px;
    font-weight: 500;
    z-index: 9999;
    background: ${type === 'success' ? '#67c23a' : '#f56c6c'};
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    transform: translateX(100%);
    opacity: 0;
    transition: all 0.3s ease;
  `
  
  document.body.appendChild(messageEl)
  
  // 显示动画
  setTimeout(() => {
    messageEl.style.transform = 'translateX(0)'
    messageEl.style.opacity = '1'
  }, 100)
  
  // 自动隐藏
  setTimeout(() => {
    messageEl.style.transform = 'translateX(100%)'
    messageEl.style.opacity = '0'
    setTimeout(() => {
      if (document.body.contains(messageEl)) {
        document.body.removeChild(messageEl)
      }
    }, 300)
  }, 3000)
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e3f0ff 0%, #a3c9f9 100%);
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.mode-switch {
  position: relative;
  display: flex;
  background: #f5f5f5;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 30px;
  overflow: hidden;
}

.switch-slider {
  position: absolute;
  top: 4px;
  left: 4px;
  width: calc(50% - 4px);
  height: calc(100% - 8px);
  background: #409eff;
  border-radius: 8px;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1;
}

.switch-slider.slide-right {
  transform: translateX(100%);
}

.switch-btn {
  flex: 1;
  padding: 12px;
  border: none;
  background: transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  transition: color 0.3s ease;
  position: relative;
  z-index: 2;
}

.switch-btn.active {
  color: white;
}

.switch-btn:hover:not(.active) {
  color: #409eff;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  position: relative;
}

.form-group input {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.form-group input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 14px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.submit-btn:disabled {
  background: #a0cfff;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.error-message {
  margin-top: 16px;
  padding: 12px;
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

.message {
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }
  
  .login-header h2 {
    font-size: 20px;
  }
  
  .form-group input {
    padding: 12px 14px;
  }
  
  .submit-btn {
    padding: 12px;
  }
}
</style>
